/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import MouseSensorDriver.Calibrator;
import dynamixel.Actuator;
import java.awt.Color;
import org.math.plot.plots.LinePlot;

/**
 *
 * @author minaev
 */
public class WardrobeCalib extends javax.swing.JFrame {

    private final ActScriptAnalyzer asa;
    int cur_calib_measure = -1;
    int srcADCVal[] = new int[2];
    int srcEngVal[] = new int[2];
    //double ADCVal[] = new double[0];
    //double EngVal[] = new double[0];
    double time[] = new double[2];
    int calibADC = 0;
    int calibEng = 0;
    double bufVal[];
    double xyADC[][] = new double[2][2];
    double xyEng[][] = new double[2][2];
    LinePlot plotADC = new LinePlot("ADC plot", Color.red, xyADC);
    LinePlot plotEng = new LinePlot("Eng plot", Color.blue, xyEng);

    /**
     * Creates new form WardrobeCalib
     */
    public WardrobeCalib() {
        asa = new ActScriptAnalyzer(WardrobeFrame.getActuators());
        initComponents();
    }

    public WardrobeCalib(ActScriptAnalyzer asa) {
        this.asa = asa;
        initComponents();
        this.setLocationRelativeTo(null);
        pp_graph.addPlot(plotADC);
        pp_graph.addPlot(plotEng);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pp_graph = new org.math.plot.Plot2DPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jtf_coef_eng_prop = new javax.swing.JTextField();
        jtf_coef_eng_offset = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jl_calib_eng = new javax.swing.JLabel();
        jcb_eng_visible = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jcb_measure = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jtf_coef_adc_prop = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtf_coef_adc_offset = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jl_calib_adc = new javax.swing.JLabel();
        jcb_adc_visible = new javax.swing.JCheckBox();
        jb_apply = new javax.swing.JButton();
        jb_save = new javax.swing.JButton();

        jLabel4.setText("EngProp:");

        jtf_coef_eng_prop.setText("1");

        jtf_coef_eng_offset.setText("0");

        jLabel5.setText("EngOffset:");

        jLabel7.setText("Calib channel:");

        jl_calib_eng.setText("0");

        jcb_eng_visible.setSelected(true);
        jcb_eng_visible.setText("Visible");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtf_coef_eng_prop)
                    .addComponent(jtf_coef_eng_offset)))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_calib_eng)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_eng_visible)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jtf_coef_eng_prop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtf_coef_eng_offset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jl_calib_eng)
                    .addComponent(jcb_eng_visible)))
        );

        jLabel1.setText("Measure:");

        jcb_measure.setModel(asa);
        jcb_measure.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcb_measureActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_measure, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
            .addComponent(jcb_measure, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jLabel2.setText("ADCProp:");

        jtf_coef_adc_prop.setText("1");

        jLabel3.setText("ADCOffset:");

        jtf_coef_adc_offset.setText("0");

        jLabel6.setText("Calib channel:");

        jl_calib_adc.setText("0");

        jcb_adc_visible.setSelected(true);
        jcb_adc_visible.setText("Visible");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtf_coef_adc_prop)
                    .addComponent(jtf_coef_adc_offset)))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_calib_adc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_adc_visible)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jtf_coef_adc_prop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtf_coef_adc_offset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jl_calib_adc)
                    .addComponent(jcb_adc_visible)))
        );

        jb_apply.setText("Apply");
        jb_apply.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                jb_applyMouseWheelMoved(evt);
            }
        });
        jb_apply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_applyActionPerformed(evt);
            }
        });

        jb_save.setText("Save");
        jb_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_saveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pp_graph, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jb_apply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jb_save, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pp_graph, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jb_apply)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jb_save)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jcb_measureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcb_measureActionPerformed
        cur_calib_measure = jcb_measure.getSelectedIndex();
        if (cur_calib_measure != -1) {
            bufVal = asa.getCalibADCTorque(cur_calib_measure);

            srcADCVal = new int[bufVal.length];
            xyADC = new double[2][bufVal.length];
            srcEngVal = new int[bufVal.length];
            xyEng = new double[2][bufVal.length];
            xyADC[0] = asa.getTime(cur_calib_measure);
            xyEng[0] = asa.getTime(cur_calib_measure);

            calibADC = asa.getADCCalibChannel(
                    asa.getADCChNums()[cur_calib_measure]);
            jl_calib_adc.setText("" + calibADC);
            for (int i = 0; i < bufVal.length; i++) {
                //srcADCVal[i] = Calibrator.get().getSourceData(calibADC, bufVal[i]);
                srcADCVal[i] = (int) Math.round(asa.getADCTorque(cur_calib_measure)[i]);
            }


            bufVal = asa.getCalibTorque(cur_calib_measure);
            calibEng = asa.getEngCalibChannel(
                    asa.getEngNums()[cur_calib_measure],
                    asa.getADCChNums()[cur_calib_measure]);
            jl_calib_eng.setText("" + calibEng);

            for (int i = 0; i < bufVal.length; i++) {
                //srcEngVal[i] = Calibrator.get().getSourceData(calibEng, bufVal[i]);
                srcEngVal[i] = (int) Math.round(asa.getTorque(cur_calib_measure)[i]);
            }

            jtf_coef_adc_prop.setText("" + Calibrator.get().getCoefsProp(calibADC));
            jtf_coef_adc_offset.setText("" + Calibrator.get().getCoefsOffset(calibADC));

            jtf_coef_eng_prop.setText("" + Calibrator.get().getCoefsProp(calibEng));
            jtf_coef_eng_offset.setText("" + Calibrator.get().getCoefsOffset(calibEng));

            updateGraphs();
        }
    }//GEN-LAST:event_jcb_measureActionPerformed

    private void jb_applyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_applyActionPerformed
        updateGraphs();
    }//GEN-LAST:event_jb_applyActionPerformed

    private void jb_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_saveActionPerformed
        Calibrator.get().saveCoefs();
    }//GEN-LAST:event_jb_saveActionPerformed

    private void jb_applyMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_jb_applyMouseWheelMoved
        double newADCProp = Double.valueOf(jtf_coef_adc_prop.getText());
        double newEngProp = Double.valueOf(jtf_coef_eng_prop.getText());
        double oldADCProp = Calibrator.get().getCoefsProp(calibADC);
        double oldEngProp = Calibrator.get().getCoefsProp(calibEng);
        if (newADCProp != oldADCProp) {
            jtf_coef_adc_offset.setText(
                    (Double.valueOf(jtf_coef_adc_offset.getText())
                    * newADCProp / oldADCProp) + "");
        }
        if (newEngProp != oldEngProp) {
            jtf_coef_eng_offset.setText(
                    (Double.valueOf(jtf_coef_eng_offset.getText())
                    * newEngProp / oldEngProp) + "");
        }
        updateGraphs();
    }//GEN-LAST:event_jb_applyMouseWheelMoved

    void updateGraphs() {
        Calibrator.get().setCoefsProp(calibADC, Double.valueOf(jtf_coef_adc_prop.getText()));
        Calibrator.get().setCoefsOffset(calibADC, Double.valueOf(jtf_coef_adc_offset.getText()));
        Calibrator.get().setCoefsProp(calibEng, Double.valueOf(jtf_coef_eng_prop.getText()));
        Calibrator.get().setCoefsOffset(calibEng, Double.valueOf(jtf_coef_eng_offset.getText()));

        for (int i = 0; i < srcADCVal.length; i++) {
            xyADC[1][i] = Calibrator.get().getData(calibADC, srcADCVal[i]);
            xyEng[1][i] = Calibrator.get().getData(calibEng, srcEngVal[i]);
        }

        /*plotADC = new LinePlot("ADC plot", Color.red, xyADC);
         plotEng = new LinePlot("Eng plot", Color.blue, xyEng);*/
        pp_graph.removeAllPlots();
        if (jcb_adc_visible.isSelected()) {
            pp_graph.addLinePlot("ADC", Color.red, xyADC[0], xyADC[1]);
        }
        if (jcb_eng_visible.isSelected()) {
            pp_graph.addLinePlot("Eng", Color.blue, xyEng[0], xyEng[1]);
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WardrobeCalib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WardrobeCalib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WardrobeCalib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WardrobeCalib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new WardrobeCalib().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jb_apply;
    private javax.swing.JButton jb_save;
    private javax.swing.JCheckBox jcb_adc_visible;
    private javax.swing.JCheckBox jcb_eng_visible;
    private javax.swing.JComboBox jcb_measure;
    private javax.swing.JLabel jl_calib_adc;
    private javax.swing.JLabel jl_calib_eng;
    private javax.swing.JTextField jtf_coef_adc_offset;
    private javax.swing.JTextField jtf_coef_adc_prop;
    private javax.swing.JTextField jtf_coef_eng_offset;
    private javax.swing.JTextField jtf_coef_eng_prop;
    private org.math.plot.Plot2DPanel pp_graph;
    // End of variables declaration//GEN-END:variables
}
